<template>
  <div class="guest-management management-page">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-card" shadow="never">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="会议ID">
          <el-input
            v-model="searchForm.meetId"
            placeholder="请输入会议ID"
            clearable
            style="width: 170px"
          />
        </el-form-item>
        <el-form-item class="search-buttons">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 嘉宾列表 -->
    <el-card class="list-card" shadow="never">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span class="header-title">嘉宾列表</span>
            <el-tag type="info" class="header-count" size="small">
              共 {{ total }} 条
            </el-tag>
          </div>
          <div class="header-operations">
            <el-button type="primary" @click="showAddDialog">
              <el-icon><Plus /></el-icon>添加嘉宾
            </el-button>
            <el-button 
              type="danger" 
              :disabled="!selectedGuests.length"
              @click="handleBatchDelete"
            >
              <el-icon><Delete /></el-icon>
              批量删除 {{ selectedGuests.length ? `(${selectedGuests.length})` : '' }}
            </el-button>
          </div>
        </div>
      </template>
      <el-table 
        :data="guestList" 
        style="width: 100%" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="嘉宾照片" width="100">
          <template #default="{ row }">
            <el-image
              :src="row.imgUrl"
              :preview-src-list="[row.imgUrl]"
              fit="cover"
              style="width: 60px; height: 60px; border-radius: 50%"
            />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="嘉宾姓名" min-width="120" />
        <el-table-column prop="title" label="嘉宾头衔" min-width="150" />
        <el-table-column prop="introduction" label="嘉宾介绍" min-width="200" show-overflow-tooltip />
        <el-table-column label="出席会议" min-width="150">
          <template #default="{ row }">
            {{ String(row.meetId) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑嘉宾对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加嘉宾' : '编辑嘉宾'"
      width="600px"
    >
      <el-form
        ref="guestFormRef"
        :model="guestForm"
        :rules="guestRules"
        label-width="100px"
      >
        <el-form-item label="嘉宾姓名" prop="name">
          <el-input v-model="guestForm.name" placeholder="请输入嘉宾姓名" />
        </el-form-item>
        
        <el-form-item label="嘉宾头衔" prop="title">
          <el-input v-model="guestForm.title" placeholder="请输入嘉宾头衔" />
        </el-form-item>
        
        <el-form-item label="嘉宾照片" prop="imgUrl">
          <el-upload
            class="guest-photo-upload"
            :auto-upload="false"
            :show-file-list="true"
            :limit="1"
            accept="image/*"
            :on-change="handlePhotoChange"
            :on-remove="handlePhotoRemove"
          >
            <template #default>
              <el-button type="primary">选择照片</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                请上传嘉宾照片，只能上传 jpg/png 文件
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="嘉宾介绍" prop="introduction">
          <el-input
            v-model="guestForm.introduction"
            type="textarea"
            rows="4"
            placeholder="请输入嘉宾介绍"
          />
        </el-form-item>

        <el-form-item label="出席会议" prop="meetId">
          <el-input 
            v-model="guestForm.meetId" 
            placeholder="请输入会议ID"
            type="text"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Plus, Delete, Search, Refresh } from '@element-plus/icons-vue'
import { getGuestList, addGuest, updateGuest, deleteGuest, uploadGuestImage } from '@/api/guest'
import type { Guest, GuestResponse } from '@/api/guest'
import { MeetingType } from '@/api/meeting'

// 搜索表单
const searchForm = reactive({
  meetId: '' as string
})

// 表单数据
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const guestFormRef = ref<FormInstance>()
const submitting = ref(false)

const guestForm = reactive({
  id: '',
  name: '',
  title: '',
  imgUrl: '',
  introduction: '',
  meetId: '',
  image: null as File | null
})

// 表单校验规则
const guestRules = reactive<FormRules>({
  name: [{ required: true, message: '请输入嘉宾姓名', trigger: 'blur' }],
  title: [{ required: true, message: '请输入嘉宾头衔', trigger: 'blur' }],
  introduction: [{ required: true, message: '请输入嘉宾介绍', trigger: 'blur' }],
  meetId: [{ required: true, message: '请选择出席的会议', trigger: 'change' }],
})

const loading = ref(false)
const guestList = ref<Guest[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedGuests = ref<Guest[]>([])

// 获取会议类型显示文本
// const getMeetingTypeLabel = (type: MeetingType): string => {
//   const map: Record<MeetingType, string> = {
//     [MeetingType.ALL]: '全部类型',
//     [MeetingType.MAIN]: '主论坛',
//     [MeetingType.PARALLEL]: '平行会议',
//     [MeetingType.SCIENCE]: '科普论坛',
//     [MeetingType.PRODUCT]: '新品发布',
//     [MeetingType.ECOLOGY]: '生态合作论坛'
//   }
//   return map[type] || '未知类型'
// }

// 获取嘉宾列表
const fetchGuestList = async () => {
  loading.value = true
  try {
    const response = await getGuestList({
      page: currentPage.value,
      size: pageSize.value,
      meetId: searchForm.meetId || undefined
    })
    console.log("response", response)
    guestList.value = response.current_data.map(guest => ({
      ...guest,
      meetId: String(guest.meetId)
    }))
    total.value = response.total_record
  } catch (error) {
    console.error('获取嘉宾列表失败:', error)
    ElMessage.error('获取嘉宾列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchGuestList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.meetId = ''
  handleSearch()
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchGuestList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchGuestList()
}

// 照片上传处理
const handlePhotoChange = (file: any) => {
  // 优化文件类型检查，同时检查MIME类型和文件扩展名
  const allowedMimeTypes = ['image/jpeg', 'image/png']
  const fileName = file.name || ''
  const extension = fileName.split('.').pop()?.toLowerCase() || ''
  const allowedExtensions = ['jpg', 'jpeg', 'png']
  
  // 只要满足一种检查方式就通过
  const isValidType = allowedMimeTypes.includes(file.type || '') || 
                      allowedExtensions.includes(extension)
                      
  if (!isValidType) {
    ElMessage.error('只能上传 JPG/PNG 格式的图片')
    return false
  }
  
  // 检查文件大小
  const maxSize = 5 * 1024 * 1024 // 5MB
  if (file.size && file.size > maxSize) {
    ElMessage.error('图片大小不能超过 5MB')
    return false
  }
  
  // 保存文件对象，等待提交时上传
  guestForm.image = file.raw
  return true
}

const handlePhotoRemove = () => {
  guestForm.imgUrl = ''
  guestForm.image = null
}

// 显示添加对话框
const showAddDialog = () => {
  dialogType.value = 'add'
  Object.assign(guestForm, {
    id: '',
    name: '',
    title: '',
    imgUrl: '',
    introduction: '',
    meetId: '',
    image: null
  })
  dialogVisible.value = true
}

// 编辑嘉宾
const handleEdit = (row: Guest) => {
  dialogType.value = 'edit'
  Object.assign(guestForm, {
    ...row,
    meetId: String(row.meetId)
  })
  dialogVisible.value = true
}

// 删除嘉宾
const handleDelete = (row: Guest) => {
  ElMessageBox.confirm('确认删除该嘉宾？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteGuest(row.id)
      ElMessage.success('删除成功')
      fetchGuestList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 表格选择处理
const handleSelectionChange = (selection: Guest[]) => {
  selectedGuests.value = selection
}

// 批量删除
const handleBatchDelete = () => {
  if (!selectedGuests.value.length) {
    ElMessage.warning('请选择要删除的嘉宾')
    return
  }

  ElMessageBox.confirm(
    `确认删除选中的 ${selectedGuests.value.length} 个嘉宾吗？此操作不可恢复！`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      loading.value = true
      for (const guest of selectedGuests.value) {
        await deleteGuest(guest.id)
      }
      ElMessage.success('批量删除成功')
      selectedGuests.value = []
      fetchGuestList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    } finally {
      loading.value = false
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!guestFormRef.value) return
  
  try {
    await guestFormRef.value.validate()
    
    if (!guestForm.image) {
      ElMessage.warning('请上传嘉宾照片')
      return
    }

    submitting.value = true
    
    const imageResponse = await uploadGuestImage(guestForm.image)
    const imageUrl = imageResponse
    if (!imageUrl) {
      throw new Error('图片上传失败')
    }

    const guestData: GuestResponse = {
      name: guestForm.name,
      title: guestForm.title,
      introduction: guestForm.introduction,
      meetId: String(guestForm.meetId),
      imgUrl: imageUrl.toString()
    }

    if (dialogType.value === 'add') {
      await addGuest(guestData)
      ElMessage.success('添加成功')
    } else {
      await updateGuest(guestForm.id, guestData)
      ElMessage.success('更新成功')
    }

    dialogVisible.value = false
    fetchGuestList()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(error instanceof Error ? error.message : '提交失败')
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  fetchGuestList()
})
</script>

<style lang="scss" scoped>
@import '@/styles/common.scss';

.guest-management {
  .guest-avatar {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    overflow: hidden;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .avatar-placeholder {
    width: 80px;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
    border-radius: 50%;
    color: #909399;
  }

  .guest-upload {
    @extend .upload-container;
  }

  .status-tag {
    min-width: 80px;
    text-align: center;
  }
}
</style> 